package com.hx.zhg.web.interceptor;

import com.hx.zhg.constant.CommonConstant;
import com.hx.zhg.constant.LOG;
import com.hx.zhg.service.vo.RequestLogVo;
import com.hx.zhg.util.RemoteClientUtil;
import com.hx.zhg.web.util.RequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @description: 请求处理拦截器
 */
@Component
public class RequestLogInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = LOG.REQUEST_LOG;
    // requestLog变量的key值
    private static final String REQUEST_LOG_VARIABLE = "requestLog";

    public RequestLogInterceptor() {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        String requestURI = request.getRequestURI();
        RequestLogVo requestLog = (RequestLogVo) request.getAttribute(REQUEST_LOG_VARIABLE);
        if (requestLog != null && !requestURI.equals("/ping") && !requestURI.equals("/ping")) {
            Long endTime = System.currentTimeMillis();
            // 得到请求耗时
            requestLog.setCostTime(endTime - requestLog.getCostTime());
            //获取用户id
            String userIdStr = request.getHeader(CommonConstant.HEADER_USERID);
            if (StringUtils.isNotBlank(userIdStr)) {
                int userId = Integer.parseInt(userIdStr);
                requestLog.setUserId(userId);
            } else {
                requestLog.setUserId(CommonConstant.INTEGER_DEFAULT);
            }
            // 记录到本地日志
            log.info(requestLog.toString());
        }
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request,
                                               HttpServletResponse response, Object handler) throws Exception {

        super.afterConcurrentHandlingStarted(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 获取Ip地址，如果没有则返回""
        String ip = RemoteClientUtil.getIpAddr(request); // IP
        String relativeUrl = request.getRequestURI(); // 相对路径
        String userAgent = RequestUtil.getUserAgent(request);
        Long startTime = System.currentTimeMillis();

        RequestLogVo requestLog = new RequestLogVo();
        requestLog.setIp(ip);
        requestLog.setRelativeUrl(relativeUrl);
        requestLog.setRequestTime(new Date());
        requestLog.setUserAgent(userAgent == null ? "" : userAgent);
        requestLog.setCostTime(startTime);
        request.setAttribute(REQUEST_LOG_VARIABLE, requestLog);
        return super.preHandle(request, response, handler);
    }

}
